package com.xc.sys.controller;

import com.xc.common.object.Constant;
import com.xc.common.tool.SendSms;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Random;

@RestController
@RequestMapping({ "/help" })
public class HelpToolController {
	
	@CrossOrigin(origins = "*", allowedHeaders = {"*"}, methods = {RequestMethod.GET})
	@RequestMapping({ "/getCurrentTime" })
	public String getCurrentTime(String pattern) {
		DateTimeFormatter fmt = DateTimeFormatter.ofPattern(pattern);
		return fmt.format(LocalDateTime.now());
	}
	@CrossOrigin(origins = "*", allowedHeaders = {"*"}, methods = {RequestMethod.GET})
	@RequestMapping({ "/getYzm" })
	public HashMap<String,Object> getYzm(HttpServletRequest request) throws Exception {
		String phone = request.getParameter("phone");
		Random random = new Random();
		String code = (Math.abs(random.nextInt()) + "").substring(0,6);
		code = StringUtils.rightPad(code, 6);
		Integer send = SendSms.send(phone, code);
		HashMap<String,Object> map = new HashMap<>();
		if (send==1){
			map.put("code",1);
			map.put("msg","获取验证码失败");
			return map;
		}
		Constant.yzmCache.put(phone, code);
		map.put("code",0);
		map.put("msg","获取验证码成功");
		return map;
	}
	@CrossOrigin(origins = "*", allowedHeaders = {"*"}, methods = {RequestMethod.GET})
	@RequestMapping({ "/checkYzm" })
	public HashMap<String,String> getMobileCode(HttpServletRequest request) {
		HashMap<String,String> map = new HashMap<String, String>();
		String userId = request.getParameter("userId");
		String ocode = request.getParameter("code");
		String code = Constant.yzmCache.getIfPresent(userId);
		if(code==null) {
			map.put("code","1");
			map.put("msg","验证码错误");
		}else {
			if(!ocode.equals(code)) {
				map.put("code","1");
				map.put("msg","验证码错误。");
			}else {
				map.put("code","0");
				map.put("msg","验证码正确");
			}
			
		}
		return map;
	}
}
